<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Docker," />










<meta name="description" content="&amp;emsp;&amp;emsp;在Docker的世界里有三个基本概念：  镜像（Image） 容器（Container） 仓库（Repository）  &amp;emsp;&amp;emsp;镜像就像一个打包好的应用程序，仓库则是应用程序的市场。我们去仓库下载镜像，然后在容器中运行这个镜像。容器的本质类似一个运行的进程，他是镜像的运行环境。Docker镜像极大地简化了应用的安装运行，我们不仅需要学会使用镜像运行容器，还">
<meta name="keywords" content="Docker">
<meta property="og:type" content="article">
<meta property="og:title" content="拥抱Docker（二）Dockerfile制作镜像">
<meta property="og:url" content="http://yoursite.com/2019/06/04/拥抱Docker（二）Dockerfile制作镜像/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="&amp;emsp;&amp;emsp;在Docker的世界里有三个基本概念：  镜像（Image） 容器（Container） 仓库（Repository）  &amp;emsp;&amp;emsp;镜像就像一个打包好的应用程序，仓库则是应用程序的市场。我们去仓库下载镜像，然后在容器中运行这个镜像。容器的本质类似一个运行的进程，他是镜像的运行环境。Docker镜像极大地简化了应用的安装运行，我们不仅需要学会使用镜像运行容器，还">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-24T16:22:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="拥抱Docker（二）Dockerfile制作镜像">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;在Docker的世界里有三个基本概念：  镜像（Image） 容器（Container） 仓库（Repository）  &amp;emsp;&amp;emsp;镜像就像一个打包好的应用程序，仓库则是应用程序的市场。我们去仓库下载镜像，然后在容器中运行这个镜像。容器的本质类似一个运行的进程，他是镜像的运行环境。Docker镜像极大地简化了应用的安装运行，我们不仅需要学会使用镜像运行容器，还">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/06/04/拥抱Docker（二）Dockerfile制作镜像/"/>





  <title>拥抱Docker（二）Dockerfile制作镜像 | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/06/04/拥抱Docker（二）Dockerfile制作镜像/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">拥抱Docker（二）Dockerfile制作镜像</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-06-04T16:47:45+08:00">
                2019-06-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Docker/" itemprop="url" rel="index">
                    <span itemprop="name">Docker</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/06/04/拥抱Docker（二）Dockerfile制作镜像/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2019/06/04/拥抱Docker（二）Dockerfile制作镜像/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&emsp;&emsp;在Docker的世界里有三个基本概念：</p>
<ul>
<li>镜像（Image）</li>
<li>容器（Container）</li>
<li>仓库（Repository）</li>
</ul>
<p>&emsp;&emsp;镜像就像一个打包好的应用程序，仓库则是应用程序的市场。我们去仓库下载镜像，然后在容器中运行这个镜像。容器的本质类似一个运行的进程，他是镜像的运行环境。Docker镜像极大地简化了应用的安装运行，我们不仅需要学会使用镜像运行容器，还需要学会如何去制作一款镜像，所以下面的任务是谈谈如何使用Dockerfile来制作一款镜像。<br><a id="more"></a></p>
<h4 id="制作一个简单的nginx镜像"><a href="#制作一个简单的nginx镜像" class="headerlink" title="制作一个简单的nginx镜像"></a>制作一个简单的nginx镜像</h4><p>&emsp;&emsp;第一步先制作一个简单的nginx镜像，新建一个Dockerfile文件：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mkdir dockerFile_demo</span><br><span class="line"><span class="built_in">cd</span> dockerFile_demo</span><br><span class="line">touch Dockerfile</span><br></pre></td></tr></table></figure></p>
<p>这个dockerFile_demo文件夹是本次镜像制作的构建环境，另外新建了一个Dockerfile文件用于指令的编写。下面往Dockerfile文件填充内容，目的是构建一个简单的nginx镜像<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">FROM</span> alpine:latest</span><br><span class="line"><span class="keyword">MAINTAINER</span> matrix22</span><br><span class="line"><span class="keyword">RUN</span><span class="bash"> apk --update add nginx &amp;&amp; mkdir -p /run/nginx</span></span><br><span class="line"><span class="keyword">EXPOSE</span> <span class="number">80</span></span><br><span class="line"><span class="keyword">CMD</span><span class="bash"> [<span class="string">"nginx"</span>, <span class="string">"-g"</span>, <span class="string">"daemon off;"</span>]</span></span><br></pre></td></tr></table></figure></p>
<p>在dockerFile_demo目录下执行命令：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker build -t nginx:simple .</span><br></pre></td></tr></table></figure></p>
<p>可以看到控制台输出：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">Sending build context to Docker daemon  2.048kB</span><br><span class="line">Step 1/5 : FROM alpine:latest</span><br><span class="line"> ---&gt; 055936d39205</span><br><span class="line">Step 2/5 : MAINTAINER matrix22</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 2aae3fb920c6</span><br><span class="line">Removing intermediate container 2aae3fb920c6</span><br><span class="line"> ---&gt; 2a7ad15ebfe6</span><br><span class="line">Step 3/5 : RUN apk --update add nginx &amp;&amp; mkdir -p /run/nginx</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 0260c7eca156</span><br><span class="line">fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz</span><br><span class="line">fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz</span><br><span class="line">(1/2) Installing pcre (8.42-r1)</span><br><span class="line">(2/2) Installing nginx (1.14.2-r1)</span><br><span class="line">Executing nginx-1.14.2-r1.pre-install</span><br><span class="line">Executing busybox-1.29.3-r10.trigger</span><br><span class="line">OK: 7 MiB <span class="keyword">in</span> 16 packages</span><br><span class="line">Removing intermediate container 0260c7eca156</span><br><span class="line"> ---&gt; 2ceae67570c9</span><br><span class="line">Step 4/5 : EXPOSE 80</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 6b4c59181b41</span><br><span class="line">Removing intermediate container 6b4c59181b41</span><br><span class="line"> ---&gt; 5bdb22de5041</span><br><span class="line">Step 5/5 : CMD [<span class="string">"nginx"</span>, <span class="string">"-g"</span>, <span class="string">"daemon off;"</span>]</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 1a4abfa8b505</span><br><span class="line">Removing intermediate container 1a4abfa8b505</span><br><span class="line"> ---&gt; babffb918e6f</span><br><span class="line">Successfully built babffb918e6f</span><br><span class="line">Successfully tagged nginx:simple</span><br></pre></td></tr></table></figure></p>
<p>一个简单的nginx镜像制作完毕，下面来查看一下这个nginx镜像在不在：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:dockerFile_demo luyun$ docker images</span><br><span class="line">REPOSITORY                                 TAG                 IMAGE ID            CREATED             SIZE</span><br><span class="line">nginx                                      simple              babffb918e6f        <span class="number">10</span> minutes ago      <span class="number">8.28</span>MB</span><br><span class="line">alpine                                     latest              <span class="number">055936</span>d39205        <span class="number">3</span> weeks ago         <span class="number">5.53</span>MB</span><br><span class="line">nginx                                      latest              <span class="number">53f</span>3fd8007f7        <span class="number">3</span> weeks ago         <span class="number">109</span>MB</span><br></pre></td></tr></table></figure></p>
<p>第一个就是我们制作的nginx镜像，下面试着运行这个TAG为simple的nginx镜像：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:~ luyun$ docker run -d -p <span class="number">80</span>:<span class="number">80</span> nginx:simple</span><br><span class="line"><span class="number">2e901416375184224613</span>ef81f2ef8aef9c14ce110d2d4daacb16443d28d3f6c4</span><br><span class="line">luyundeMacBook-Pro:~ luyun$ docker ps</span><br><span class="line">CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES</span><br><span class="line"><span class="number">2e9014163751</span>        nginx:simple        <span class="string">"nginx -g 'daemon of…"</span>   <span class="number">5</span> seconds ago       Up <span class="number">4</span> seconds        <span class="number">0.0</span>.0.0:<span class="number">80</span>-&gt;<span class="number">80</span>/tcp   vigorous_carson</span><br></pre></td></tr></table></figure></p>
<p>可以看到我们成功使用nginx:simple创建了nginx容器。</p>
<h4 id="Dockerfile常用指令"><a href="#Dockerfile常用指令" class="headerlink" title="Dockerfile常用指令"></a>Dockerfile常用指令</h4><p>Dockerfile的每一条指令都是对镜像做出一次修改，每次修改都会提交一个新的镜像层。</p>
<h5 id="FROM"><a href="#FROM" class="headerlink" title="FROM"></a>FROM</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">FROM</span> &lt;镜像&gt;</span><br></pre></td></tr></table></figure>
<p>FROM是Dockerfile中第一条指令，它指定了一个基础镜像，后续的指令都是基于此镜像。上面nginx的例子基于alpine镜像，而alpine镜像基于Alpine Linux操作系统，Alpine Linux是轻量级的Linux发行版。每一个Dockerfile文件都必须继承于一个基础镜像，除了alpine这些操作系统镜像，Docker Hub上还有非常多高质量的官方镜像，如nginx、redis、mysql、tomcat等。除此之外，Docker还存在一个特殊的镜像scratch，这个镜像其实是一个虚拟的镜像，实际并不存在。如果你不想以任何镜像为基础，那么可以指定scratch作为基础镜像。</p>
<h5 id="MAINTAINER"><a href="#MAINTAINER" class="headerlink" title="MAINTAINER"></a>MAINTAINER</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">MAINTAINER</span> &lt;作者&gt;</span><br></pre></td></tr></table></figure>
<p>指定镜像作者</p>
<h5 id="EXPOSE"><a href="#EXPOSE" class="headerlink" title="EXPOSE"></a>EXPOSE</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">EXPOSE</span> &lt;端口&gt; [&lt;端口<span class="number">1</span>&gt;...]</span><br></pre></td></tr></table></figure>
<p>声明运行时容器提供服务的端口，注意声明并不是指运行时就使用这个端口。在使用<strong>docker run -P</strong>运行容器的时候，会自动映射EXPOSE的端口。</p>
<h5 id="RUN"><a href="#RUN" class="headerlink" title="RUN"></a>RUN</h5><p>最常用的指令之一，用于执行命令。之前说过，Dockerfile中每一条指令都会建立一层镜像，RUN指令也是如此，为了避免生成太多的镜像，一般用<strong>&amp;&amp;</strong>将各个命令联合起来，这样就不会生成多余的镜像。RUN指令有两种格式：</p>
<ul>
<li><strong>shell: RUN &lt;命令&gt;</strong></li>
<li><strong>exec: RUN [“可执行文件”, “参数1”, “参数2”]</strong></li>
</ul>
<h5 id="CMD"><a href="#CMD" class="headerlink" title="CMD"></a>CMD</h5><p>容器启动的时候执行命令，同RUN一样有两种格式。</p>
<h5 id="ENTRYPOINT"><a href="#ENTRYPOINT" class="headerlink" title="ENTRYPOINT"></a>ENTRYPOINT</h5><p>ENTRYPOINT和CMD类似，CMD命令有一个特点，它可以被docker run后面的命令参数替换掉，而ENTRYPOINT不会。</p>
<h5 id="COPY"><a href="#COPY" class="headerlink" title="COPY"></a>COPY</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">COPY</span><span class="bash"> &lt;源路径&gt; &lt;目标路径&gt;</span></span><br><span class="line"><span class="keyword">COPY</span><span class="bash"> [<span class="string">"&lt;源路径1&gt;"</span>... <span class="string">"&lt;目标路径&gt;"</span>]</span></span><br></pre></td></tr></table></figure>
<p>复制构建上下文目录（比如上面例子中的dockerFile_demo）下的文件或者文件夹到目标路径下，源路径可以有多个。</p>
<h5 id="ADD"><a href="#ADD" class="headerlink" title="ADD"></a>ADD</h5><p>类似COPY但是拥有更多高级功能，官方推荐使用COPY，所以这里不多介绍。</p>
<h5 id="ENV"><a href="#ENV" class="headerlink" title="ENV"></a>ENV</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ENV</span> &lt;键&gt; &lt;值&gt;</span><br><span class="line"><span class="keyword">ENV</span> &lt;键<span class="number">1</span>&gt;=&lt;值<span class="number">1</span>&gt; &lt;键<span class="number">2</span>&gt;=&lt;值<span class="number">2</span>&gt; ...</span><br></pre></td></tr></table></figure>
<p>设置环境变量，后面的指令或者运行中的应用都可以使用这个环境变量</p>
<h5 id="VOLUME"><a href="#VOLUME" class="headerlink" title="VOLUME"></a>VOLUME</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">VOLUME</span><span class="bash"> [<span class="string">"&lt;路径1&gt;"</span>, <span class="string">"&lt;路径2&gt;"</span>...]</span></span><br><span class="line"><span class="keyword">VOLUME</span><span class="bash"> &lt;路径&gt;</span></span><br></pre></td></tr></table></figure>
<p>在容器内存储数据，数据层会随着容器的删除而删除，Docker采用volume（卷）的形式来向容器提供持久化存储：<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">VOLUME</span><span class="bash"> /data</span></span><br></pre></td></tr></table></figure></p>
<p>任何向/data中写入的数据都会写入一个匿名的数据卷中，即使容器被删除了，这些数据依然会保留。</p>
<h5 id="WORKDIR"><a href="#WORKDIR" class="headerlink" title="WORKDIR"></a>WORKDIR</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">WORKDIR</span><span class="bash"> [路径]</span></span><br></pre></td></tr></table></figure>
<p>指定容器内的一个目录， 在容器内执行的命令会在该目录下执行。</p>
<h5 id="ONBUILD"><a href="#ONBUILD" class="headerlink" title="ONBUILD"></a>ONBUILD</h5><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ONBUILD</span> [指令]</span><br></pre></td></tr></table></figure>
<p>ONBUILD比较特殊，它后面会跟着其他的Dockerfile指令，比如RUN、CMD等，不过这些指令不会在当前镜像构建时立即执行，只有以当前镜像为基础镜像，去构建下一级镜像的时候才会被执行。</p>
<h4 id="重新制作nginx镜像"><a href="#重新制作nginx镜像" class="headerlink" title="重新制作nginx镜像"></a>重新制作nginx镜像</h4><p>&emsp;&emsp;上面制作的nginx镜像其实有点问题，如果在浏览器中输入localhost就会发现只有一个404页面。我们可以使用<strong>docker exec</strong>进入容器内查看nginx的配置：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:dockerFile_demo luyun$ docker ps</span><br><span class="line">CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES</span><br><span class="line">c33c19767e22        nginx:simple        <span class="string">"nginx -g 'daemon of…"</span>   3 seconds ago       Up 1 second         0.0.0.0:80-&gt;80/tcp   vigilant_dewdney</span><br><span class="line">luyundeMacBook-Pro:dockerFile_demo luyun$ docker <span class="built_in">exec</span> -it c33c19767e22 /bin/sh</span><br><span class="line">/ <span class="comment"># ls</span></span><br><span class="line">bin    dev    etc    home   lib    media  mnt    opt    proc   root   run    sbin   srv    sys    tmp    usr    var</span><br></pre></td></tr></table></figure></p>
<p>进入/etc/nginx/conf.d目录查看default.conf文件：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">        listen 80 default_server;</span><br><span class="line">        listen [::]:80 default_server;</span><br><span class="line"></span><br><span class="line">        <span class="comment"># Everything is a 404</span></span><br><span class="line">        location / &#123;</span><br><span class="line">                <span class="built_in">return</span> 404;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment"># You may need this to prevent return 404 recursion.</span></span><br><span class="line">        location = /404.html &#123;</span><br><span class="line">                internal;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个配置默认就是转到一个404页面。现在我们来修改刚才的nginx镜像，添加一份自己定制的conf配置，比如我们让nginx转发到百度，在dockerFile_demo目录下新建server.conf文件：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:dockerFile_demo luyun$ touch server.conf</span><br></pre></td></tr></table></figure></p>
<p>在server.conf中添加nginx配置：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">        listen       80;</span><br><span class="line">        server_name  localhost;</span><br><span class="line">        location / &#123;</span><br><span class="line">            <span class="comment">#root   html;</span></span><br><span class="line">            <span class="comment">#index  index.html index.htm;</span></span><br><span class="line">        &#125;</span><br><span class="line">        location /baidu/&#123;            </span><br><span class="line">            proxy_pass https://www.baidu.com/;                   </span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#error_page  404              /404.html;</span></span><br><span class="line">        <span class="comment"># redirect server error pages to the static page /50x.html</span></span><br><span class="line">        <span class="comment">#</span></span><br><span class="line">        error_page   500 502 503 504  /50x.html;</span><br><span class="line">        location = /50x.html &#123;</span><br><span class="line">            root   html;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>修改之前的DockerFile文件，将conf配置加入镜像中，并且挂载nginx日志到宿主盘上：<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">FROM</span> alpine:latest</span><br><span class="line"><span class="keyword">MAINTAINER</span> matrix22</span><br><span class="line"><span class="keyword">RUN</span><span class="bash"> apk --update add nginx &amp;&amp; mkdir -p /run/nginx</span></span><br><span class="line"><span class="keyword">ADD</span><span class="bash"> server.conf /etc/nginx/conf.d/</span></span><br><span class="line"><span class="keyword">VOLUME</span><span class="bash"> [ <span class="string">"/var/log/nginx"</span> ]</span></span><br><span class="line"><span class="keyword">EXPOSE</span> <span class="number">80</span></span><br><span class="line"><span class="keyword">CMD</span><span class="bash"> [<span class="string">"nginx"</span>, <span class="string">"-g"</span>, <span class="string">"daemon off;"</span>]</span></span><br></pre></td></tr></table></figure></p>
<p>在控制台运行:<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker build -t nginx:baidu .</span><br></pre></td></tr></table></figure></p>
<p>可以看到输出成功的日志：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:dockerFile_demo luyun$ docker build -t nginx:baidu .</span><br><span class="line">Sending build context to Docker daemon  3.584kB</span><br><span class="line">Step 1/7 : FROM alpine:latest</span><br><span class="line"> ---&gt; 055936d39205</span><br><span class="line">Step 2/7 : MAINTAINER matrix22</span><br><span class="line"> ---&gt; Using cache</span><br><span class="line"> ---&gt; 2a7ad15ebfe6</span><br><span class="line">Step 3/7 : RUN apk --update add nginx &amp;&amp; mkdir -p /run/nginx</span><br><span class="line"> ---&gt; Using cache</span><br><span class="line"> ---&gt; 2ceae67570c9</span><br><span class="line">Step 4/7 : ADD server.conf /etc/nginx/conf.d/</span><br><span class="line"> ---&gt; 5880d069d097</span><br><span class="line">Step 5/7 : VOLUME [ <span class="string">"/var/log/nginx"</span> ]</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 910ceacd51ad</span><br><span class="line">Removing intermediate container 910ceacd51ad</span><br><span class="line"> ---&gt; dbb0663ef250</span><br><span class="line">Step 6/7 : EXPOSE 80</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> 65ac86ff9d9c</span><br><span class="line">Removing intermediate container 65ac86ff9d9c</span><br><span class="line"> ---&gt; b36ce6335d34</span><br><span class="line">Step 7/7 : CMD [<span class="string">"nginx"</span>, <span class="string">"-g"</span>, <span class="string">"daemon off;"</span>]</span><br><span class="line"> ---&gt; Running <span class="keyword">in</span> f2c2ff08635f</span><br><span class="line">Removing intermediate container f2c2ff08635f</span><br><span class="line"> ---&gt; 4a9c8000ac42</span><br><span class="line">Successfully built 4a9c8000ac42</span><br><span class="line">Successfully tagged nginx:baidu</span><br></pre></td></tr></table></figure></p>
<p>使用docker run指令运行nginx:baidu：<br><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker <span class="keyword">run</span><span class="bash"> -d -p 80:80 nginx:baidu</span></span><br></pre></td></tr></table></figure></p>
<p>在浏览器中输入 <a href="http://localhost/baidu/" target="_blank" rel="noopener">http://localhost/baidu/</a> ，就可以看到百度的页面了。使用<strong>docker inspect</strong>命令查看对应容器挂载信息：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"Mounts"</span>: [</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">"Type"</span>: <span class="string">"volume"</span>,</span><br><span class="line">                <span class="string">"Name"</span>: <span class="string">"2689a4cafb8e6f5a65eade36559dfa5e2742c5de371b90788774876bd268c277"</span>,</span><br><span class="line">                <span class="string">"Source"</span>: <span class="string">"/var/lib/docker/volumes/2689a4cafb8e6f5a65eade36559dfa5e2742c5de371b90788774876bd268c277/_data"</span>,</span><br><span class="line">                <span class="string">"Destination"</span>: <span class="string">"/var/log/nginx"</span>,</span><br><span class="line">                <span class="string">"Driver"</span>: <span class="string">"local"</span>,</span><br><span class="line">                <span class="string">"Mode"</span>: <span class="string">""</span>,</span><br><span class="line">                <span class="string">"RW"</span>: <span class="keyword">true</span>,</span><br><span class="line">                <span class="string">"Propagation"</span>: <span class="string">""</span></span><br><span class="line">            &#125;</span><br><span class="line">        ]</span><br></pre></td></tr></table></figure></p>
<p>不过这里有个小问题，由于我是使用Mac安装的Docker，尝试进入这个<strong>/var/lib/docker/volumes/</strong>就会报错找不到这个文件夹：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:~ luyun$ <span class="built_in">cd</span> /var/lib/docker/volumes/</span><br><span class="line">-bash: <span class="built_in">cd</span>: /var/lib/docker/volumes/: No such file or directory</span><br></pre></td></tr></table></figure></p>
<p>Mac下查看挂载的文件信息比较复杂，需要进入以下目录：</p>
<blockquote>
<p><strong>~/Library/Containers/com.docker.docker/Data/vms/0/</strong></p>
</blockquote>
<p>进入后看到一个tty文件，使用screen连接：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">luyundeMacBook-Pro:~ luyun$ <span class="built_in">cd</span> ~/Library/Containers/com.docker.docker/Data/vms/0/</span><br><span class="line">luyundeMacBook-Pro:0 luyun$ ls</span><br><span class="line">00000002.000005f4	Docker.qcow2		hyperkit.pid</span><br><span class="line">00000002.00001000	config.iso		<span class="built_in">log</span></span><br><span class="line">00000002.00001001	connect			nic1.uuid</span><br><span class="line">00000002.0000f3a5	guest.000005f5		tty</span><br><span class="line">00000003.000005f5	guest.00000948</span><br><span class="line">00000003.00000948	hyperkit.json</span><br><span class="line">luyundeMacBook-Pro:0 luyun$ screen tty</span><br></pre></td></tr></table></figure></p>
<p>然后进入Docker的宿主目录：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">linuxkit-025000000001:~<span class="comment"># cd /var/lib/docker/volumes/2689a4cafb8e6f5a65eade36559d</span></span><br><span class="line">fa5e2742c5de371b90788774876bd268c277/_data</span><br><span class="line">linuxkit-025000000001:/var/lib/docker/volumes/2689a4cafb8e6f5a65eade36559dfa5e2742c5de371b90788774876bd268c277/_data<span class="comment"># ls</span></span><br><span class="line">access.log  error.log</span><br></pre></td></tr></table></figure></p>
<p>可以看到nginx的日志，打开access.log可以看到访问的日志了：<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">172.17.0.1 - - [03/Jun/2019:13:37:31 +0000] <span class="string">"GET /baidu/ HTTP/1.1"</span> 200 39612 <span class="string">"-"</span></span><br><span class="line">172.17.0.1 - - [03/Jun/2019:13:48:14 +0000] <span class="string">"GET /baidu/ HTTP/1.1"</span> 200 39921 <span class="string">"-"</span></span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Docker/" rel="tag"># Docker</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/27/拥抱Docker（一）常用命令/" rel="next" title="拥抱Docker（一）常用命令">
                <i class="fa fa-chevron-left"></i> 拥抱Docker（一）常用命令
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/06/24/分布式共识算法之Paxos/" rel="prev" title="分布式共识算法之Paxos">
                分布式共识算法之Paxos <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#制作一个简单的nginx镜像"><span class="nav-number">1.</span> <span class="nav-text">制作一个简单的nginx镜像</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Dockerfile常用指令"><span class="nav-number">2.</span> <span class="nav-text">Dockerfile常用指令</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#FROM"><span class="nav-number">2.1.</span> <span class="nav-text">FROM</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#MAINTAINER"><span class="nav-number">2.2.</span> <span class="nav-text">MAINTAINER</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#EXPOSE"><span class="nav-number">2.3.</span> <span class="nav-text">EXPOSE</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#RUN"><span class="nav-number">2.4.</span> <span class="nav-text">RUN</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#CMD"><span class="nav-number">2.5.</span> <span class="nav-text">CMD</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ENTRYPOINT"><span class="nav-number">2.6.</span> <span class="nav-text">ENTRYPOINT</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#COPY"><span class="nav-number">2.7.</span> <span class="nav-text">COPY</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ADD"><span class="nav-number">2.8.</span> <span class="nav-text">ADD</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ENV"><span class="nav-number">2.9.</span> <span class="nav-text">ENV</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#VOLUME"><span class="nav-number">2.10.</span> <span class="nav-text">VOLUME</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#WORKDIR"><span class="nav-number">2.11.</span> <span class="nav-text">WORKDIR</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ONBUILD"><span class="nav-number">2.12.</span> <span class="nav-text">ONBUILD</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#重新制作nginx镜像"><span class="nav-number">3.</span> <span class="nav-text">重新制作nginx镜像</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2019/06/04/拥抱Docker（二）Dockerfile制作镜像/';
          this.page.identifier = '2019/06/04/拥抱Docker（二）Dockerfile制作镜像/';
          this.page.title = '拥抱Docker（二）Dockerfile制作镜像';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
